package org.binge.widget.service;

import com.net263.sequence.SequenceFactory;
import org.binge.widget.facade.BpFileService;
import org.binge.widget.facade.ParserExcelService;
import org.binge.widget.util.ReadExcelUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Kid on 2016/4/28.
 * 支持文档说明：XLS/XLSX类型
 */
@Service("commonParserExcelService")
public class ParserExcelServiceImpl implements ParserExcelService {

    @Autowired
    SequenceFactory defaultSequenceFactory;

    @Autowired
    private BpFileService bpFileService;

    private static final int parseCount = 1000;//一次解析的条数(解析该条数后,跳出进行入库操作)

    @Override
    public long createSequenceFileId(String sequenceName) throws Exception {
        long fileID = -1;
        try {
            fileID = defaultSequenceFactory.getNextValue(sequenceName);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return fileID;
    }

    @Override
    public void ParseExcelFile(String remotePathAndName, Map fileMap) throws Exception {
        try {
            List resultList = null;
            int currentCount = 0;
            //设置入库参数
            Map<String, Long> lineAndColMap = new HashMap<>();
            lineAndColMap.put("fileId", (long) fileMap.get("fileId"));
            lineAndColMap.put("dataId", (long) fileMap.get("dataId"));
            lineAndColMap.put("initSum", 0L);
            lineAndColMap.put("successSum", 0L);
            lineAndColMap.put("errorSum", 0L);
            do {
                resultList = ReadExcelUtil.readExcel(remotePathAndName, currentCount, parseCount);
                //调用入库服务
                if (resultList.size() != 0) {
                    lineAndColMap = bpFileService.insertLineAndCol(resultList, fileMap, lineAndColMap);
                    //当前计数+上一次解析数
                    currentCount += parseCount;
                }
            } while (resultList.size() != 0);
            bpFileService.updateFileAndData(fileMap, lineAndColMap);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}